import axios from 'axios'
import { useUserInfo } from '@/stores/useInfoStore'
import { ElMessage } from 'element-plus'
import 'element-plus/theme-chalk/src/message.scss'

import router from '@/router'

// 创建axios实例
const http = axios.create({
  baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 10000,
})

// axios请求拦截器
http.interceptors.request.use(
  (config) => {
    //1.从pinia中获取数据
    const userStore = useUserInfo()
    //2.按照后端要求拼接token数据
    const token = userStore.userInfo.token
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (e) => Promise.reject(e),
)

// axios响应式拦截器
http.interceptors.response.use(
  (res) => res.data,
  (e) => {
    ElMessage({
      type: 'warning',
      message: e.response.data.message,
    })
    //401token处理
    //1.清除本地用户数据
    //2.跳转到登录页
    if (e.response.status === 401) {
      useUserInfo().cleaInfo()
      router.push('/login')
    }
    return Promise.reject(e)
  },
)

export default http
